package com.goat.controller;

import com.goat.model.element.BaseElement;
import com.goat.model.manager.EleManager;
import com.goat.model.manager.enumCls.GameElement;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 键盘监听类
 */

public class GameListener4Key implements KeyListener {
    //维护一个管理器
    private EleManager eleManager;

    private static Set<Integer> set=new HashSet<Integer>();

    public GameListener4Key() {
        this.eleManager = EleManager.getEleManager();
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        //这里的逻辑要结合Player的代码来理解
        //如果集合包含了此key，就不用重复的改变状态，下面的代码不用执行，提高效率
        //Player中只是改变方向的状态
        if(set.contains(e.getKeyCode())){
            return;
        }

        //如果没有，则添加，以后就可以判断了
        set.add(e.getKeyCode());
        //System.out.println(e.getKeyCode());
        Map<GameElement, List<BaseElement>> map = eleManager.getGameElements();
        List<BaseElement> players = map.get(GameElement.PLAYER);
        for (BaseElement baseElement :players) {
            baseElement.keyListen(true,e.getKeyCode());
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        //与上面同理
        if(!set.contains(e.getKeyCode())){
            return;
        }


        set.remove(e.getKeyCode());
        Map<GameElement, List<BaseElement>> map = eleManager.getGameElements();
        List<BaseElement> players = map.get(GameElement.PLAYER);
        for (BaseElement baseElement :players) {
            baseElement.keyListen(false,e.getKeyCode());
        }
    }
}
